require 'Emitter'
require 'erb'

INBUILT_TYPES = [:int, :date, :string, :long, :byte, :boolean, :decimal]

template = <<-EOF
package <%=flex_pkg%>
{
  [Bindable]
  [RemoteClass(alias="<%=java_pkg%>.<%=t.name%>")]
  public class <%=t.name%>  {
     
     public function <%=t.name%>() {
       //TODO: Implement function
     }
     <%t.attrs.each do |attr|%>
     private var _<%=tmp_name(attr)%>:<%=tmp_type(attr)%>;
     <%end%><%t.elms.each do |elem|%>
     private var _<%=tmp_name(elem)%>:<%=tmp_type(elem)%>;
     <%end%><%t.attrs.each do |attr|%>
     public function get <%=tmp_name(attr)%>():<%=tmp_type(attr)%> {
       return this._<%=tmp_name(attr)%>;
     }
     
     public function set <%=tmp_name(attr)%>(value:<%=tmp_type(attr)%>):void {
       this._<%=tmp_name(attr)%> = value; 
     }<%end%>
     <%t.elms.each do |elem|%>
     public function get <%=tmp_name(elem)%>():<%=tmp_type(elem)%> {
       return this._<%=tmp_name(elem)%>;
     }
     
     public function set <%=tmp_name(elem)%>(value:<%=tmp_type(elem)%>):void {
       this._<%=tmp_name(elem)%> = value; 
     }
     <%end%>
  }
} 
EOF
ASMAPPINGS = {
  :string => 'String',
  :List => 'ArrayCollection',
  :int => 'int',
  :date => 'Date',
  :long => 'long',
  :byte => 'byte',
  :boolean => 'Boolean',
  :decimal => 'decimal'
}
def tmp_name(entity)
  entity.name[0].chr.downcase.concat(entity.name[1..entity.name.length])  
end
def tmp_type(entity)
  # If it's not an inbuild type, skip the mappings lookup part since
  # we are not keeping custom mapping for user defined classes. E.g. if the
  # type of an element/attribute is Policy and if it isn't a list, we should
  # return Policy. For all other cases, we do a lookup.
  return entity.type.name if !INBUILT_TYPES.include?(entity.type) && !entity.list
  entity.list ?  ASMAPPINGS[:List] : ASMAPPINGS[entity.type]
end

erb = ERB.new(template, 0, '%<>')
emit = Emitter.new('./config/sbs.xsd')
type_map = emit.parse()
flex_pkg = "flex.ws"
java_pkg = "home.proj"
type_map.each_value do |type|
  next if INBUILT_TYPES.include?(type.name)  
  t = type
  result = erb.result(binding)
  File.new('./data/' << type.name.to_s << '.as', 'w').write(result)
end


